package com.boful.convert.core.impl.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public class ReadProcessThread implements Runnable {
	private Process process;
	private Logger logger = Logger.getLogger(ReadProcessThread.class);

	public Process getProcess() {
		return process;
	}

	public void setProcess(Process process) {
		this.process = process;
	}

	class ReadThread implements Runnable {
		private InputStream inputStream;

		public InputStream getInputStream() {
			return inputStream;
		}

		public void setInputStream(InputStream inputStream) {
			this.inputStream = inputStream;
		}

		public ReadThread(InputStream inputStream) {
			super();
			this.inputStream = inputStream;
		}

		@Override
		public void run() {
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			String line = null;
			try {
				while ((line = bufferedReader.readLine()) != null) {
					logger.debug(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	public ReadProcessThread(Process process) {
		super();
		this.process = process;
	}

	@Override
	public void run() {

		InputStream inputStream = process.getInputStream();
		InputStream errorStream = process.getErrorStream();
		Thread thread1 = new Thread(new ReadThread(inputStream));
		Thread thread2 = new Thread(new ReadThread(errorStream));

		thread1.start();
		thread2.start();

		while (true) {
			if (thread1.getState() == Thread.State.TERMINATED
					|| thread2.getState() == Thread.State.TERMINATED) {
				try {
					inputStream.close();
					errorStream.close();
				} catch (Exception e) {
					logger.error(e);
				}
				break;
			}
		}
	}

}
